package org.cloud.framework.utils;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlUtils {

    public static Document getDocument(InputStream aInputStream) throws DocumentException {
        //File file = new File(filePath);
        SAXReader saxReader = new SAXReader();
        Document doc = saxReader.read(aInputStream);
        return doc;
    }

    /**
     *  资源类型
     * @param aInputStream 文件路径
     * @return
     * @throws DocumentException
     */
    public static List<Map<String,String>> getResources(InputStream aInputStream) throws DocumentException {
        Document doc = getDocument(aInputStream);
        List<Element> resources = doc.selectNodes("//resources/resource");
        List<Map<String,String>> lm = new ArrayList<>();
        Map<String,String> m = null;
        for (Element resource:resources) {
            m = new HashMap<>();
            List<Attribute> attributes = resource.attributes();
            for (Attribute attribute : attributes) {
                m.put(attribute.getName(),attribute.getValue());
            }
            if(!m.isEmpty()){
                lm.add(m);
                m = null;
            }
        }
        return lm;
    }

    /**
     *  资源字段
     * @param aInputStream 文件路径
     * @param nameEn 资源英文名称
     * @return
     * @throws DocumentException
     */
    public static  List<Map<String,Object>> getFields(InputStream aInputStream,String nameEn) throws DocumentException {
        Document doc = getDocument(aInputStream);
        List<Element> fields = doc.selectNodes("//resources/resource[@nameEn='"+nameEn+"']/field");
        List<Map<String,Object>> lm = new ArrayList<>();
        Map<String,Object> m = null;
        for (Element field:fields) {
            m = new HashMap<>();
            Attribute type = field.attribute("type");
            if(type.getValue().equals("select") || type.getValue().equals("tree")){
                List<Element> valuesAttr = field.elements();
                List<Map<String,Object>> values = new ArrayList<>();
                Map<String,Object> v = null;
                for (Element value:valuesAttr) {
                    v = new HashMap<>();
                    List<Attribute> attributes = value.attributes();
                    for (Attribute attribute:attributes) {
                        v.put(attribute.getName(),attribute.getValue());
                    }
                    if(!v.isEmpty()){
                        values.add(v);
                        v = null;
                    }
                }
                m.put("value",values);
                List<Attribute> attributes = field.attributes();
                for (Attribute attribute : attributes) {
                    m.put(attribute.getName(),attribute.getValue());
                }
                if(!m.isEmpty()){
                    lm.add(m);
                    m = null;
                }
            }else{
                List<Attribute> attributes = field.attributes();
                for (Attribute attribute : attributes) {
                    m.put(attribute.getName(),attribute.getValue());
                }
                if(!m.isEmpty()){
                    lm.add(m);
                    m = null;
                }
            }
        }
        return lm;
    }
    public static  void createXml(Map<String,String> data,String nameEn,String path) throws Exception {
        Document doc = DocumentHelper.createDocument();
        //增加根节点
        Element books = doc.addElement("entity");
        //增加子元素
        Element element = null;
        for (String key:data.keySet()) {
            element = books.addElement(key);
            element.setText("<![CDATA[" + data.get(key) +"]]>");
            element = null;
        }
        //实例化输出格式对象
        OutputFormat format = OutputFormat.createPrettyPrint();
        //设置输出编码
        format.setEncoding("UTF-8");
        //创建需要写入的File对象
        File file = new File(path);
        //生成XMLWriter对象，构造函数中的参数为需要输出的文件流和格式
        XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
        //开始写入，write方法中包含上面创建的Document对象
        writer.write(doc);
    }
    public static String stripNonValidXMLChars(String str) {
        if (str == null || "".equals(str)) {
            return str;
        }
        String s = "";
        char[] charArray = str.toCharArray();
        for (char c : charArray) {
            if (!(c < 0x9 || c > 0x9 && c < 0xA || c > 0xA && c < 0xD || c > 0xD && c
                    < 0x20 || c > 0xD7FF && c < 0xE000 || c > 0xFFFD)){//下面了允许的字符范围

                s += c;
            }
        }
        return s;
    }
}
